import React from "react";
import {getAdministrativeDivisions} from "../../service/api";
import { Tree, Spin } from 'antd';
const TreeNode = Tree.TreeNode;
import './Trees.less';
class Trees extends React.Component {

    state = {
        data: [],
        loading: true
    }

    componentDidMount() {
        let self = this;
        if(sessionStorage.getItem("administrativeDivisions")){
            self.setState({
                data: JSON.parse(sessionStorage.getItem("administrativeDivisions")),
                loading: false
            });
        }else{
            getAdministrativeDivisions().then(function (data) {
                if(data.code === 200){
                    self.setState({
                        data: data.data,
                        loading: false
                    });
                    sessionStorage.setItem("administrativeDivisions",JSON.stringify(data.data))
                }
            })
        }

    }

    renderTreeNodes = (data) => {
        return data.map((item) => {
            if (item.children) {
                return (
                    <TreeNode title={item.regionname} key={item.id} dataRef={item}>
                        {this.renderTreeNodes(item.children)}
                    </TreeNode>
                );
            }
            return <TreeNode {...item} title={item.name} dataRef={item} />;
        });
    }

    onSelect = (value)=> {
        this.props.getId(value);
    }

    render(){
        let tree = this.renderTreeNodes(this.state.data);
        return (
            <Spin spinning={this.state.loading}>
                <div className="trees">
                    {this.state.data.length?<Tree showLine onSelect={this.onSelect} defaultExpandedKeys={['4', '20', '21']}>
                        {tree}
                    </Tree>:true
                    }
                </div>
            </Spin>

        )
    }

}

export default Trees;